package com.yykj.common.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.lang.reflect.Type;

/**
 * Created by chendg on 2018/3/6 0006.
 */
public class GsonUtil {

	private static Gson gson;

	public static Gson getInstance() {
		if (gson == null) {
			GsonBuilder builder = new GsonBuilder();
			gson = builder.create();
		}
		return gson;
	}

	public static String toJson(Object obj) {
		return getInstance().toJson(obj);
	}

	public static JsonObject fromJson(String jsonStr) {
		return getInstance().fromJson(jsonStr, JsonObject.class);
	}

	public static <T> T fromJson(String json, Class<T> clazz) {
		return getInstance().fromJson(json, clazz);
	}

	public static String toKeyValueJson(String... params) {
		if (null == params) {
			return null;
		}
		JsonObject jsonObject = new JsonObject();
		int len = params.length;
		for (int i = 0; i < len; i += 2) {
			if (i + 1 < len) {
				jsonObject.addProperty(params[i], params[i + 1]);
			}
		}
		return getInstance().toJson(jsonObject);
	}

	public static <T> T fromJson(String json, Type type) {
		return getInstance().fromJson(json, type);
	}

}
